<template>
  <div>
    <TopFilter ref="searchOrdersPanel" :list="searchOrdersList" :cols="3" :rows="2" :label-width="90" @filterChange="changeHandle" @onCollapse="collapseHandle" />
    <FilterTable
      ref="table"
      columnsRef="finance_repairFinance_receivables_maintable"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      selectionType="single"
      :datakey="'rows'"
      :onSyncTableData="
        () => {
          this.collapseHandle();
        }
      "
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="arr => (this.onChangeColumn = arr)"
    >
      <template slot="controls">
        <el-button type="primary" @click="openPayments">收 款</el-button>
        <!-- <el-button type="primary" @click="hanldeDebtPay">欠款收款</el-button> -->
        <!-- <el-button type="primary" :loading="batchCancelBtnLoading" :disabled="batchCancelBtnLoading" @click="handleCancelSettelement">取消收银</el-button> -->
        <el-button v-show="is_auth" type="primary" @click="openReduction">减 免</el-button>
        <el-button type="primary" @click="openWriteOff">销 账</el-button>
        <el-button type="primary" @click="exportExcelReceiveData">导 出</el-button>
      </template>
    </FilterTable>
    <BaseDialog :visible.sync="showReceiptsDetail" title="收款明细" width="800px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <receiptsDetail :rowData="rowData" ref="receiptsDetail" @close="closeReceiptsDetail" />
    </BaseDialog>
    <BaseDialog :visible.sync="showPayments" title="收款" width="900px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <payments ref="payments" @close="closePayments" />
    </BaseDialog>
    <BaseDialog :visible.sync="showReduction" title="减免" width="900px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <reduction ref="reduction" @close="closeReduction" />
    </BaseDialog>
    <BaseDialog :visible.sync="showWriteOff" title="销账" width="900px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <writeOff ref="writeOff" :selectRow="onChangeColumn" @close="closeWriteOff" />
    </BaseDialog>
  </div>
</template>

<script>
import moment from 'moment';
import dictCode from '@/utils/dictCode';
import { dictionary } from '@/utils/dictMixin';
import { exportExcelFile } from '@/utils/index';
import { getJxsSelect, getOrderList, getRepairType, exportExcelData, batchCancelCollection } from '@/api/finance/repair/receivables';
import { getReceivedlist, exportReceiveMoney, getAllDealer, getAllUser } from '@/api/repair/repairFinance/index.js';
import receiptsDetail from './receiptsDetail';
import payments from './payments';
import reduction from './reduction';
import writeOff from './writeOff';
import { isAuthorized } from '@/utils/index';

export default {
  name: 'Receivables',
  components: {
    receiptsDetail,
    payments,
    reduction,
    writeOff
  },
  mixins: [dictionary],
  data() {
    return {
      searchOrdersList: this.createSearchOrdersList(),
      columns: this.createTableColumns(),
      fetchParams: { xhrAbort: false },
      fetchApi: getReceivedlist,
      onChangeColumn: [],
      showReceiptsDetail: false,
      showPayments: false,
      showReduction: false,
      showWriteOff: false,
      rowData: {},
      // 是否可以减免
      is_auth: false,
      batchCancelBtnLoading: false,
      allDealer: []
    };
  },

  computed: {},
  watch: {},
  mounted() {
    this.getAuth();
    this.getAllDealer();
    this.getAllUser();
  },
  methods: {
    // 获取所有的经销商
    async getAllDealer() {
      let res = await getAllDealer();
      if (res.resultCode == 200) {
        let allDealer = res.data.map(x => ({ text: x.dealerShortname, value: x.dealerCode + '' }));
        this.allDealer = allDealer;
        // this.columns.find(x => x.dataIndex === 'ownerCode').dictItems = allDealer;
      }
    },
    async getAllUser() {
      let res = await getAllUser();
      if (res.resultCode == 200) {
        let allUser = res.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
        this.columns.find(x => x.dataIndex === 'SERVICE_ADVISOR').dictItems = allUser;
      }
    },
    getAuth() {
      this.is_auth = true;
      // // 是否可减免的权限
      // if (isAuthorized('1314', '13141005')) {
      //   this.is_auth = true;
      // } else {
      //   this.is_auth = false;
      // }
    },
    createSearchOrdersList() {
      return [
        {
          type: 'INPUT',
          label: '结算单号',
          fieldName: 'balanceNo'
        },
        {
          type: 'INPUT',
          label: '工单号',
          fieldName: 'roNo'
        },
        {
          type: 'INPUT',
          label: '配件销售单号',
          fieldName: 'salesPartNo'
        },
        {
          type: 'SELECT',
          label: '是否结清',
          fieldName: 'payOff',
          itemList: this.createDictList('1004')
        },
        {
          type: 'INPUT',
          label: '收费对象代码',
          fieldName: 'paymentObjectCode'
        },
        {
          type: 'INPUT',
          label: '收费对象名称',
          fieldName: 'paymentObjectName'
        },

        {
          type: 'INPUT',
          label: '车主',
          fieldName: 'ownerName'
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license'
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin'
        },

        {
          type: 'SELECT',
          label: '是否提交索赔',
          fieldName: 'isClaim',
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '是否已开票',
          fieldName: 'invoiceTag',
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '是否欠款结算',
          fieldName: 'arrBalance',
          itemList: this.createDictList('1004')
        },
        {
          type: 'RANGE_DATE',
          label: '结算时间',
          style: { minWidth: '200px' },
          fieldName: 'balanceTimeBegin|balanceTimeEnd'
        },
        {
          type: 'RANGE_DATE',
          label: '结清时间',
          style: { minWidth: '200px' },
          fieldName: 'squareDateBegin|squareDateEnd'
        },
        {
          type: 'RANGE_DATE',
          label: '提交索赔时间',
          style: { minWidth: '200px' },
          fieldName: 'claimStartDate|claimEndDate'
        },
        {
          type: 'RANGE_DATE',
          label: '开票时间',
          style: { minWidth: '200px' },
          fieldName: 'invoiceTagStartDate|invoiceTagEndDate'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          // fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 110,
          // fixed: 'left',
          render: props => {
            return (
              <el-button size="mini" type="text" onClick={() => this.openReceiptsDetail(props.row)}>
                收款明细
              </el-button>
            );
          }
        },
        {
          title: '经销商代码',
          dataIndex: 'OWNER_CODE',
          width: 150,
          sorter: true,
          filter: true,
          showOverflowTooltip: true,
          filterType: 'input'
        },
        {
          title: '经销商名称',
          dataIndex: 'ownerShortName',
          width: 150,
          sorter: true,
          filter: true,
          showOverflowTooltip: true,
          filterType: 'input',
          render: props => {
            // 不能翻译就显示code
            let ownerShortName = props.row.OWNER_CODE;
            if (this.allDealer.length) {
              let item = this.allDealer.find(x => x.value == props.row.OWNER_CODE);
              if (item) {
                ownerShortName = item.text;
                props.row.ownerShortName = item.text; // 每一条数据增加一个字段，后台不存前端显示用
              }
            }
            return <span>{ownerShortName}</span>;
          }
        },
        {
          title: '是否提交索赔',
          dataIndex: 'IS_CLAIM',
          sorter: true,
          dictItems: this.createDictList('1004')
        },
        {
          title: '是否欠款结算',
          dataIndex: 'ARR_BALANCE',
          sorter: true,
          dictItems: this.createDictList('1004')
        },
        {
          title: '结算单号',
          dataIndex: 'BALANCE_NO',
          sorter: true
        },
        {
          title: '结算时间',
          dataIndex: 'BALANCE_TIME',
          sorter: true,
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '结清时间',
          dataIndex: 'SQUARE_DATE',
          sorter: true,
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '提交索赔时间',
          dataIndex: 'CLAIM_CREATE_DATE',
          sorter: true,
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '开票时间',
          dataIndex: 'INVOICE_DATE',
          sorter: true,
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '收费对象代码',
          dataIndex: 'PAYMENT_OBJECT_CODE',
          sorter: true
        },
        {
          title: '收费对象名称',
          dataIndex: 'PAYMENT_OBJECT_NAME',
          sorter: true
        },
        {
          title: '应收账款',
          dataIndex: 'RECEIVABLE_AMOUNT',
          sorter: true
        },
        {
          title: '已收账款',
          dataIndex: 'RECEIVED_AMOUNT',
          sorter: true
        },
        {
          title: '已免账款',
          dataIndex: 'DERATED_AMOUNT',
          sorter: true
        },
        {
          title: '未收账款',
          dataIndex: 'NOT_RECEIVED_AMOUNT',
          sorter: true
        },
        {
          title: '是否已开票',
          dataIndex: 'INVOICE_TAG',
          sorter: true,
          dictItems: this.createDictList('1004')
        },
        {
          title: '是否结清',
          dataIndex: 'PAY_OFF',
          sorter: true,
          dictItems: this.createDictList('1004')
        },
        {
          title: '工单号',
          dataIndex: 'RO_NO',
          sorter: true,
          width: 130,
          showOverflowTooltip: true
        },
        {
          title: '配件销售单号',
          dataIndex: 'SALES_PART_NO',
          sorter: true
        },
        {
          title: '服务顾问',
          dataIndex: 'SERVICE_ADVISOR',
          sorter: true
        },
        {
          title: '车主编号',
          dataIndex: 'OWNER_NO',
          sorter: true,
          minWidth: 160
        },
        {
          title: '车主',
          dataIndex: 'OWNER_NAME',
          sorter: true
        },
        {
          title: '车牌号',
          dataIndex: 'LICENSE',
          sorter: true
        },
        {
          title: 'VIN',
          dataIndex: 'VIN',
          sorter: true,
          minWidth: 160
        },
        {
          title: '维修类型',
          dataIndex: 'REPAIR_TYPE_NAME',
          sorter: true
        }
      ];
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.$refs.table.$refs.pageTable.EXECUTE_RESET_HEIGHT();
      });
    },
    async getJxsSelect() {
      const res = await getJxsSelect();
      // console.log(res)
      this.searchOrdersList.find(item => item.fieldName === 'dealerCode').itemList = res.map(x => ({ value: x.DEALER_CODE, text: x.ASC_SHORTNAME }));
    },

    changeHandle(val) {
      this.fetchParams = Object.assign({}, val);
    },
    openReceiptsDetail(data) {
      this.showReceiptsDetail = true;
      this.rowData = { ...data };
    },
    closeReceiptsDetail() {
      this.showReceiptsDetail = false;
    },
    // 点击收款
    openPayments(data) {
      if (this.onChangeColumn.length > 0) {
        this.showPayments = true;
        this.$nextTick(() => {
          this.$refs.payments.openModel(this.onChangeColumn);
        });
      } else {
        this.$notify.info({ title: '提示信息', message: '请选择表格数据' });
      }
    },
    closePayments(refresh) {
      if (refresh) {
        this.fetchParams = { ...this.fetchParams };
      }
      this.showPayments = false;
    },
    openReduction(data) {
      console.log('select', this.onChangeColumn);
      if (this.onChangeColumn.length > 0) {
        this.showReduction = true;
        this.$nextTick(() => {
          this.$refs.reduction.openModel(this.onChangeColumn);
        });
      } else {
        this.$notify.info({ title: '提示信息', message: '请选择表格数据' });
      }
    },

    closeReduction(val) {
      if (!val) {
        this.fetchParams = { ...this.fetchParams };
      }
      this.showReduction = false;
    },
    openWriteOff(data) {
      console.log('select', this.onChangeColumn);
      if (this.onChangeColumn.length == 1) {
        this.showWriteOff = true;
        this.rowData = { ...data };
      } else {
        this.$notify.error({ title: '提示信息', message: '请选择一条表格数据' });
      }
    },
    closeWriteOff(val) {
      if (!val) {
        this.fetchParams = { ...this.fetchParams };
      }
      this.showWriteOff = false;
    },
    exportExcelReceiveData() {
      exportReceiveMoney(this.fetchParams).then(res => {
        console.log(res);
        exportExcelFile(res.data, '维修收款');
      });
    }
  }
};
</script>

<style lang="less" scoped>
.vehicle-details-wrap {
  position: relative;
  padding-bottom: @modulePadding;
  .box {
    border: 1px solid #ccc;
    padding-top: 15px;
    padding-bottom: 15px;
    padding-right: 15px;
    border-radius: @borderRadius;
    margin-bottom: 20px;
    box-shadow: @boxShadow;
    display: flex;
    flex-direction: column;
    .el-row {
      text-align: center;
    }
  }
  .left {
    position: absolute;
    left: 0;
    width: calc(100% - 300px);
    border: 1px solid @borderColor;
    border-radius: @borderRadius;
    box-shadow: @boxShadow;
    padding: @modulePadding;
    padding-left: 0;
  }
  .right {
    margin-left: calc(100% - 280px);
    border: 1px solid @borderColor;
    border-radius: @borderRadius;
    box-shadow: @boxShadow;
    padding: @modulePadding;
  }
  .choose-style {
    color: @primaryColor;
  }
}
</style>
